import React, { Component } from "react";
import MainLayout from "@component/mainLayout/mainLayout";
import Button from "@component/button/index";
import { connect } from "react-redux";
import { InputItem, Toast, Modal } from "antd-mobile";
import BankItem from "./bankItem.js";
import "./index.scss";
import verCode from "@component/verCode/index";
import {
	addNewBank,
	setSupportedBankList,
	getSelectedBankList,
	getSupportedBankList,
	checkUserBankInfo,
	setSelectedBankCard,
	getAllSelectedBankList,
	setSelectedBankList
} from "@redux/Action/bank/bank";
import { InterfaceG } from "@config/Config";
import BackModal from "@component/backModal/index";
import yhTools from "@tools/yh";
import iconXj from "@images/icon-xj1.png";

const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkBankReg = value => /^\d{13,19}$/.test(value);

const agreementPageMap = {
	huaTongAccount: "/huaTongBankElectronicAccountServiceAgreement",
	taxStatement: "/individualTaxResidentStatusStatement",
	pay: "/agreementoflianyintong"
};
let height = window.innerHeight;
const backHomeMap = {
	601: "/xhfHomeNoCredit",
	802: "/xhdHome",
	1: "/walletHome",
	602: "/xhfHomeNoCredit"
};

const year = new Date().getFullYear();
const month = new Date().getMonth() + 1;
const day = new Date().getDate();
@verCode()
@connect(
	state => ({
		supportedBankList: state.bankReducer.supportedBankList || [],
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		ocrInfo: state.livenessReducer
	}),
	dispatch => ({
		addNewBank: value => dispatch(addNewBank(value)),
		setSupportedBankList: value => dispatch(setSupportedBankList(value)),
		setSelectedBankCard: value => dispatch(setSelectedBankCard(value)),
		setSelectedBankList: value => dispatch(setSelectedBankList(value)),
		getSelectedBankList: (value, fun) => dispatch(getSelectedBankList(value, fun)),
		getAllSelectedBankList: value => dispatch(getAllSelectedBankList(value)),
		getSupportedBankList: (value, fun) =>
			dispatch(getSupportedBankList(value, fun)),
		checkUserBankInfo: (value, fun) => dispatch(checkUserBankInfo(value, fun))
	})
)
class AddBank extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isVisible: false,
			accountNo: "",
			verifyCode: "",
			channelCode: "YHB",
			userBankPhone: "",
			messageSerialNumber: "",
			verifier: "",
			from: "",
			isBackModalVisible: false,
			hasSendCode: false,
			canSubmit: true,
			isHiddenBotton: false
		};
	}

	componentDidMount = () => {
		const from = yhTools.getUrlParam("from");
		const fromBankList = from === "bankList";
		// 宝付贷版本用的是YHB 换卡是ll连连, 连连是120s倒计时，华通是60s
		window.addEventListener("resize", () => {
			if (window.innerHeight !== height) {
				this.setState({
					isHiddenBotton: true
				});
			} else {
				this.setState({
					isHiddenBotton: false
				});
			}
		});
		this.xhdQueryTwoElement();
		this.setState(
			{
				from,
				channelCode: "ll"
			},
			() => {
				const { checkUserBankInfo, getSupportedBankList } = this.props;
				const { channelCode } = this.state;
				if (fromBankList) {
					// !ocrInfo.userName && checkUserBankInfo({ channelCode });
					// TODO 优化，支付换卡和开户绑卡银行卡列表不一样
					checkUserBankInfo({ channelCode });
				} else {
					getSupportedBankList({ channelCode });
				}
			}
		);
	};
	//获取二要素
	xhdQueryTwoElement = () => {
		let objs = {
			url: InterfaceG.xhdQueryTwoElement,
			params: {
				productNum: "802"
			}
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				this.setState({
					userName: res.data.userName,
					idNo: res.data.idNo
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	getMsgCode = () => {
		this.xhdSendCode();
	};
	sendMsgCode = () => {
		const { channelCode, accountNo, userBankPhone, from } = this.state;
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(userBankPhone)) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(from === "bankList" ? 120 : 60); //连连和华通验证码时间不一样
		const params = {
			channelCode,
			accountNo
		};
		let objs = {
			url: InterfaceG.loanBindCard,
			params:
				from === "liveness"
					? {
						...params,
						bankMobilePhone: userBankPhone
					}
					: {
						...params,
						userBankPhone
					},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);

		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				const { messageSerialNumber, verifier } = res.data;
				this.setState({
					messageSerialNumber,
					verifier,
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	//小辉贷发送验证码
	xhdSendCode() {
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		const { userBankPhone, accountNo } = this.state;
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(userBankPhone)) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(120); //连连和华通验证码时间不一样
		let objs = {
			//url: InterfaceG.xhdSendCode,
			url: InterfaceG.sendBindCardVerifyCode,
			params: {
				mobilePhone: this.state.userBankPhone,
				productNum: "802",
				accountNo,
				scene: yhTools.getUrlParam("from") ? yhTools.getUrlParam("from") : "02" //"01", "还款绑卡","02", "借款绑卡","03", "银行卡管理绑卡","04", "实名认证绑卡","05", "授信申请绑卡"
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				// const { messageSerialNumber, verifier } = res.data;
				this.setState({
					hasSendCode: true,
					orderNo: res.data.orderNo
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	openAccount = () => {
		const { applyNo, lnid } = this.props;
		const {
			accountNo,
			verifyCode,
			userBankPhone,
			messageSerialNumber
		} = this.state;
		if (this.checkCanSubmit(accountNo, userBankPhone, verifyCode)) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: InterfaceG.openAccount,
				params: {
					applyNo,
					lnid,
					cardNo: accountNo,
					verifyCode,
					bankMobilePhone: userBankPhone,
					messageSerialNumber,
					channelCode: "YHB"
				},
				_alertShow: false
			};
			Toast.loading("加载中...", 100);
			yhTools.request(objs).then(async res => {
				Toast.hide();
				this.setState({ canSubmit: true });

				if (res.code === "0") {
					const cardNo = res.data.electronicCardNo;
					this.props.history.push(
						`/openAccountResult?status=success&cardNo=${cardNo}`
					);
				} else if (
					// res.code === "60007" ||
					// res.code === "00007" ||
					// res.code === "306003" ||
					// res.code === "00053" ||
					// res.code === "99999" ||
					// res.code === "99998" ||
					// res.code === "99000"
					res.code === "2"
				) {
					Toast.info(res.message);
				} else {
					this.props.history.push(`/openAccountResult?status=fail`);
				}
			});
		}
	};
	InputOnChange = (key, value) => {
		this.setState({
			[key]: submitCardRegexp(value)
		});
	};
	updateBank = () => {
		this.chooseImage();
	};
	//获取ocr银行卡
	getOcrBank(path) {
		const imageData = {
			name: "bankImg.jpeg",
			path: path,
			params: {}
		};
		const objs = {
			url: InterfaceG.orcBank,
			imageArray: [imageData]
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			console.log(res);
			Toast.hide();
			if (res.code === "0") {
				this.setState({
					bankInfo: res.data,
					accountNo: res.data.cardNumber
					//accountNo: res.data.cardNumber.replace(/\s/g, "").replace(/(\w{4})(?=\w)/g, "$1 ")
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	//选择图片
	chooseImage() {
		//打开原生获取图片
		let imgPicker = {
			type: "3", //相机和相册
			imageName: this.props.mobile + "_card_" + ".png",
			imageSize: 100 * 1024 + "", // 100kb,自定义
			thumbnailSize: 100 * 1024 + "" // 100kb,自定义
		};

		yhTools.chooseImage(imgPicker).then(
			resp => {
				this.getOcrBank(resp.data.path);
			},
			() => { }
		);
	}
	checkCanSubmit = (cardNo, phoneNum, verifyCode) => {
		if (!cardNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		if (!checkBankReg(submitCardRegexp(cardNo))) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}
		if (!phoneNum) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(phoneNum)) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!this.state.hasSendCode) {
			Toast.info("请获取验证码", 2);
			return false;
		}
		if (!verifyCode.length) {
			Toast.info("请输入验证码");
			return false;
		}
		if (verifyCode.length !== 6) {
			Toast.info("验证码输入错误");
			return false;
		}

		return true;
	};
	/** 检查是否设置支付密码 */
	async checkSetPassword() {
		let objs = {
			url: InterfaceG.checkSetPassword,
			params: {},
			_alertShow: false
		};

		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();
		if (res.code === "0") {
			return true;
		} else if (res.code === "70010") {
			return false;
		} else {
			Toast.info(res.message, 2);
			return null;
		}
	}
	addNewBankFn = async () => {
		// 防止重复提交，待优化
		const {
			channelCode,
			accountNo,
			userBankPhone,
			verifyCode,
			orderNo,
			verifier
		} = this.state;
		if (this.checkCanSubmit(accountNo, userBankPhone, verifyCode)) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: InterfaceG.loanBindCard,
				params: {
					channelCode,
					accountNo,
					userBankPhone,
					verifyCode,
					orderNo,
					verifier,
					productNum: "802",
					scene: yhTools.getUrlParam("from")
						? yhTools.getUrlParam("from")
						: "02" //"01", "还款绑卡","02", "借款绑卡","03", "银行卡管理绑卡","04", "实名认证绑卡","05", "授信申请绑卡"
				},
				_alertShow: false
			};
			Toast.loading("加载中...");
			yhTools.request(objs).then(res => {
				this.setState({ canSubmit: true });
				if (res.code === "0") {
					this.props.getSelectedBankList({ channelCode }, () => {
						if (yhTools.getUrlParam("from") == "01") {
							//还款添加银行卡返回还款页
							let cardNo = accountNo.substr(-4);
							this.props.setSelectedBankCard(cardNo);
							this.props.history.goBack();
						} else {
							setTimeout(() => {
								this.props.history.goBack();
							}, 0);
						}
					});
				} else {
					Toast.hide();
					Toast.info(res.message, 2);
				}
			});
		}
	};
	saveBank = () => {
		this.addNewBankFn();
	};
	//小辉贷四要素认证
	xhdSubmit = () => {
		const { accountNo, verifyCode, userBankPhone } = this.state;
		if (this.checkCanSubmit(accountNo, userBankPhone, verifyCode)) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				//url: InterfaceG.xhdBindCard,
				url: InterfaceG.loanBindCard,
				params: {
					userBankPhone,
					productNum: "802",
					accountNo,
					verifyCode
				},
				_alertShow: false
			};
			Toast.loading("加载中...", 100);
			yhTools.request(objs).then(res => {
				this.setState({ canSubmit: true });
				Toast.hide();
				if (res.code === "0") {
					this.props.history.push("/editPersonalInfo");
				} else {
					Toast.info(res.message, 2);
				}
			});
		}
	};
	//查看协议
	openContract = (e, type) => {
		e.stopPropagation();
		const { userName, idNo } = this.props.ocrInfo;
		const commonParams = {
			personName: userName,
			idCardCode: idNo,
			year,
			month,
			day
		};
		const paramsHuaTong = {
			...commonParams,
			signName: userName
		};
		this.props.history.push({
			pathname: agreementPageMap[type],
			params: type === "huaTongAccount" ? paramsHuaTong : commonParams
		});
	};
	onModalClick = booleanValue => {
		this.setState({
			isBackModalVisible: false
		});
		!booleanValue && this.props.history.push(backHomeMap[this.props.lnid]);
	};
	showModal = () => {
		this.setState({
			isVisible: false,
			isBackModalVisible: true
		});
	};
	toggleVisible = isVisible => {
		this.setState({
			isVisible
		});
	};
	render() {
		const {
			isBackModalVisible,
			userBankPhone,
			from,
			isVisible,
			accountNo,
			hasSendCode,
			userName,
			idNo,
			isHiddenBotton
		} = this.state;
		const { lnid, supportedBankList } = this.props;
		console.log(isHiddenBotton, "____________");
		const _pageParams = {
			header: {
				title: "添加银行卡"
			},
			componentDidRecover: () => {
				const from = yhTools.getUrlParam("from");
				if (from == "bankList") {
					// this.setState({
					// 	userBankPhone: "",
					// 	verifyCode: "",
					// 	accountNo: "",
					// 	from: from
					// });
				}
			},
			cacheLifecycles: this.props.cacheLifecycles,
			isModal: from === "liveness",
			history: this.props.history
		};
		const { countDown, isClick } = this.props.verCode;
		return (
			<div>
				<MainLayout pageParams={_pageParams} handleBack={this.showModal}>
					<BackModal
						product={lnid}
						isVisible={isBackModalVisible}
						onClick={this.onModalClick}
					/>
					<div className="add-bank-container">
						<InputItem
							className="my-input"
							defaultValue={userName}
							value={userName}
							disabled={true}
						>
							姓名
						</InputItem>
						<InputItem
							className="my-input"
							defaultValue={idNo}
							value={idNo}
							disabled={true}
						>
							身份证号码
						</InputItem>
						<p className="title">
							请添加本人银行卡
							<i onClick={() => this.toggleVisible(true)}>支持银行列表</i>
						</p>
						{/* 23包括空格 */}
						<InputItem
							maxLength="23"
							className="my-input my-clear1"
							placeholder="请输入银行卡号"
							type="number"
							clear
							value={accountNo}
							onChange={this.InputOnChange.bind(this, "accountNo")}
						>
							银行卡号
							<img
								alt="guide"
								className="icon-help"
								src={iconXj}
								onClick={this.updateBank}
							/>
						</InputItem>
						<InputItem
							clear
							type="phone"
							placeholder="请填写预留手机号"
							defaultValue={userBankPhone}
							className="my-input"
							onChange={this.InputOnChange.bind(this, "userBankPhone")}
						>
							手机号
						</InputItem>
						<InputItem
							clear
							placeholder="请输入验证码"
							maxLength={6}
							minLength={6}
							pattern="[0-9]{6}"
							type="tel"
							className="my-input my-clear2"
							onChange={this.InputOnChange.bind(this, "verifyCode")}
						>
							验证码
							<span className="get-code" onClick={this.getMsgCode}>
								{/* {isClick ? "获取验证码" : countDown} */}

								{isClick
									? hasSendCode
										? "重新发送"
										: "获取验证码"
									: countDown}
							</span>
						</InputItem>
					</div>
					<div className="agree-wrapper">
						查看
						<a
							className="font-link2 one-line"
							onClick={e => this.openContract(e, "pay")}
						>
							《连连支付相关服务协议》
						</a>
					</div>
					<p className="tip-infor">
						我司正规持牌机构，全程信息加密处理，保障您的隐私安全
					</p>
					<Modal
						visible={isVisible}
						transparent
						maskClosable={true}
						title="银行卡支持列表"
						closable={true}
						onClose={() => this.toggleVisible(false)}
						className="bank-list-modal"
					>
						<div style={{ height: 300, overflow: "scroll" }}>
							{supportedBankList.map(item => (
								<BankItem item={item} key={Math.random()} />
							))}
						</div>
					</Modal>
					<div className="btn_xhd_addbank_save">
						<Button onClick={this.saveBank}>同意协议并添加</Button>
					</div>
				</MainLayout>
			</div>
		);
	}
}
export default AddBank;
